<?php

namespace App\Repositories;

use App\admin\Service\OA;
use App\Jobs\Fun;
use App\Models\NewsModel;
use App\Models\NewsPriseModel;
use App\Models\User\UserModel;
use App\Repositories\Admin\UserRepository;
use http\Env\Request;
use Illuminate\Support\Facades\DB;
use function MongoDB\BSON\toJSON;

class NewsRepository
{
    protected $newsModel;

    // protected $newsPriseModel;

    public function __construct()
    {
        $this->newsModel = new NewsModel;
        //  $this->newsPriseModel = new NewsPriseModel;
    }

    /**
     * 资讯列表
     * @param array $cids
     * @return array
     */
    private function private_getNews($type = 0, $uid = 0)
    {
        $where = [];
        if ($type) {
            $where['cid'] = $uid;
        }
        $result = $this->newsModel
            ->where(['status' => 0])
            ->where($where)
            ->orderBy('created_at', 'desc')
            ->select(['id', 'title', 'thumb', 'content', 'cid', 'praise'])
            ->skip(0)
            ->take(10)
            ->get();
        //   print_r($result);//exit;
        if (!count($result)) {
            return array();
        }
        // $tet=UserModel::getinfo(66);

        foreach ($result as $v) {
            //  $userModel = new UserRepository();
            $user = UserModel::getinfo($v->cid);
            $v->uname = $user ? $user['name'] : '测试用户';
            $v->head = Fun::pImg($user['head']);
            $v->thumb = Fun::pImg($v->thumb);
            $v->intro = $v->content;
            if (mb_strlen($v->content) > 20) {
                $v->intro = mb_substr($v->content, 0, 20) . '...';
            }
        }
        //  print_r($result);exit;
        return $result;
    }

    public function getNews($page = 0,$uid)
    {
            //private_getNews
        $cachelist = \Illuminate\Support\Facades\Cache::remember('getNews_' . $page, 0.1, function () use ($page) {
            $result = $this->newsModel
                ->where(['status' => 0])
                ->orderBy('paixu', 'desc')
                ->orderBy('id', 'desc')
                ->select(['id', 'title', 'thumb', 'content', 'cid', 'praise'])
                ->skip($page*10)
                ->take(10)
                ->get();
            // print_r($result);//exit;
            if (!count($result)) {
                return array();
            }
            foreach ($result as $v) {
                //  $userModel = new UserRepository();
                $user = UserModel::getinfo($v->cid);
                $v->uname = $user ? $user['name'] : '测试用户';
                $v->head = Fun::pImg($user['head']);
                $v->thumb = Fun::pImg($v->thumb);
                $v->intro = $v->content;
                if (mb_strlen($v->content) > 20) {
                    $v->intro = mb_substr($v->content, 0, 20) . '...';
                }
            }
          //  print_r($result);exit;
            return $result->toArray();
        });

        foreach ($cachelist as $key=>$vo){
            $cachelist[$key]['clickpraise']=$this->isPraise($vo['id'],$uid);
        }

        return $cachelist;
    }


    /**
     * 资讯详情
     * @param array $cids
     * @return array
     */
    public function getNewsDetail($new_id = 0)
    {
        $model = $this->newsModel
            ->where(['status' => 0, 'id' => $new_id])
            ->first(['id','title', 'thumb',
               // 'desc',
                'content', 'cid', 'praise',
                'created_at']);
        if (empty($model)) {
            return $model;
        }
        $userModel = new UserRepository();
        $user = $userModel->getShowOne($model->cid);
        $model->uname = $user ? $user->name : '测试用户';
        $model->head = $user ? $user->head : UserModel::defaultHead;
        $model->head = Fun::pImg($model->head);
        $model['time'] = Fun::date($model->created_at);
        $model['clickpraise']=$this->isPraise($new_id,OA::$user->getId());
        NewsModel::where('id',$new_id)->increment('pv', 1);//累加1
        return $model;
    }


    /**
     * 资讯点赞
     */
    public function setPraise($id, $uid)
    {
        $table = 'praise' . ($id % 10);
        $newid_uid = $id . '.' . $uid;
        $exists = DB::table($table)->where('newid_uid', $newid_uid)->exists();
        if ($exists) {
            return ['status' => false, 'msg' => '已经点赞过了'];
        }
        $db = DB::table($table);
        $db->insert([
            'newid_uid' => $newid_uid
        ]);
        $count = $this->newsModel->where('id', $id)->increment('praise');
        if ($count) {
            return ['status' => true, 'msg' => '点赞成功', 'data' => '+1'];
        } else {
            return ['status' => false, 'msg' => '操作失败'];
        }
    }

    /**
     *判断是否点过赞
     */
    public function isPraise($id, $uid)
    {
        $table = 'praise' . ($id % 10);
        $newid_uid = $id . '.' . $uid;
        return DB::table($table)->where('newid_uid', $newid_uid)->exists();
    }


    /**
     * 资讯点赞  弃用
     * @deprecated
     */
    private function setPraise_del($id, $uid)
    {
        //目前没有取消点赞，后期如果有这里还得判断是否取消点赞  TODO
        if ($this->newsPriseModel->where(['news_id' => $id, 'uid' => $uid])->exists()) {
            return ['status' => false, 'msg' => '已经点赞过了'];
        }
        $model = $this->newsModel->where('id', $id)->first();
        if (!$model) {
            return ['status' => false, 'msg' => '数据不存在'];
        }

        if ($this->newsPriseModel->insert([
            'news_id' => $id,
            'uid' => $uid,
            'gmt_create' => time(),
            'gmt_modify' => time()
        ])) {
            $praise = $model->praise + 1;
            $this->newsModel
                ->where('id', $id)
                ->update(array('praise' => $praise));
//           ->increment('praise',1);
            return ['status' => true, 'msg' => '点赞成功', 'data' => $praise];
        } else {
            return ['status' => false, 'msg' => '操作失败'];
        }
    }

    /**
     * 添加资讯
     */
    public function addNew($data)
    {
        return $this->newsModel->insert($data);
    }

    /**
     * 更新资讯
     */
    public function updateNew($id, $data)
    {
        return $this->newsModel->where('id', $id)->update($data);
    }

}